package de.hauschild.gmltracer.gml.impl.array;

import java.util.List;

import org.apache.commons.lang.text.StrBuilder;

import de.hauschild.gmltracer.gml.Environment;
import de.hauschild.gmltracer.gml.Token;
import de.hauschild.gmltracer.gml.TokenStack;
import de.hauschild.gmltracer.gml.impl.AbstractToken;
import de.hauschild.gmltracer.gml.impl.binding.IdentifierToken;

/**
 * Represents a array of {@link Token}.
 * 
 * @author Klaus Hauschild
 * @since 1.0.0
 */
public class ArrayToken extends AbstractToken {

  private final List<Token> tokens;

  /**
   * Creates as new {@link ArrayToken}.
   * 
   * @param theTokens
   *          the initial tokens
   */
  public ArrayToken(final List<Token> theTokens) {
    tokens = theTokens;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void evaluate(final Environment environment, final TokenStack tokenStack) {
    tokenStack.push(this);

    for (int i = 0; i < tokens.size(); i++) {
      final Token token = tokens.get(i);
      if (token instanceof IdentifierToken) {
        final IdentifierToken identifier = (IdentifierToken) token;
        tokens.set(i, environment.get(identifier.getName()));
      }
    }
  }

  /**
   * Gets the {@link Token} at position specified by the index.
   * 
   * @param index
   *          the index
   * 
   * @return the token
   */
  public Token get(final int index) {
    return tokens.get(index);
  }

  /**
   * Gets the length.
   * 
   * @return the length
   */
  public int getLength() {
    return tokens.size();
  }

  @Override
  public String toString() {
    final StrBuilder builder = new StrBuilder();

    builder.append("[ "); //$NON-NLS-1$
    builder.appendWithSeparators(tokens, " "); //$NON-NLS-1$
    builder.append(" ]"); //$NON-NLS-1$

    return builder.toString();
  }
}
